package com.fivefu.core.skyeye.event.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fivefu.base.common.utils.date.DateUtils;
import com.fivefu.core.skyeye.event.entity.DbAiEvent;
import com.fivefu.core.skyeye.event.mapper.DbAiEventMapper;
import com.fivefu.core.skyeye.event.services.DbAiEventImageService;
import com.fivefu.core.skyeye.event.services.DbAiEventService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fivefu.core.skyeye.event.vo.EventImageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 事件表 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-08-24 11:57:38
 */
@Service
public class DbAiEventServiceImpl extends ServiceImpl<DbAiEventMapper, DbAiEvent> implements DbAiEventService {

    @Autowired
    private DbAiEventImageService eventImageService;

    /**
     * 通过识别事件编号查询事件信息
     * @param mimirEventid 识别事件编号
     * @param sceneCode 场景编号
     * @return
     */
    @Override
    public DbAiEvent queryEventByMimirEventId(Long mimirEventid, String sceneCode){
        QueryWrapper<DbAiEvent> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("mimir_eventid",mimirEventid);
        wrapper.eq("scene_id",sceneCode);
        DbAiEvent event = baseMapper.selectOne(wrapper);
        return event;
    }

    /**
     * 编辑事件开始事件
     * @param mimirEventid 识别案卷编号
     * @param sceneCode 场景编号
     * @param cameraCode 探头编号
     * @param startTime 开始时间
     * @return
     */
    @Override
    public Long editEventStartInfo(Long mimirEventid, String sceneCode, String cameraCode, LocalDateTime startTime){
        LocalDateTime time = LocalDateTime.now();
        DbAiEvent event = new DbAiEvent();
        event.setCameraId(cameraCode);
        event.setSceneId(sceneCode);
        event.setStartTime(startTime);
        event.setUpdatedTime(time);
        event.setMimirEventid(mimirEventid);

        DbAiEvent mimirEvent = queryEventByMimirEventId(mimirEventid,sceneCode);
        if (mimirEvent != null){
            event.setId(mimirEvent.getId());
            baseMapper.updateById(event);
        }else{
            event.setCreatedTime(time);
            event.setStatus(1);//事件持续中
            baseMapper.insert(event);
        }
        return event.getId();
    }

    /**
     * 编辑事件结束事件
     * @param mimirEventid 识别事件编号
     * @param sceneCode 场景编号
     * @param endTime 结束时间
     * @return
     */
    @Override
    public Long editEventEndInfo(Long mimirEventid, String sceneCode, LocalDateTime endTime){
        DbAiEvent mimirEvent = queryEventByMimirEventId(mimirEventid,sceneCode);

        //计算间隔时长
        String time1 = DateUtils.format(mimirEvent.getStartTime(),DateUtils.DEFAULT_DATETIME_PATTERN);
        String time2 = DateUtils.format(endTime,DateUtils.DEFAULT_DATETIME_PATTERN);
        long time = DateUtils.minusSeconds(time1, time2);
        mimirEvent.setContinuedTime(time);

        mimirEvent.setEndTime(endTime);
        mimirEvent.setUpdatedTime(LocalDateTime.now());
        if (mimirEvent.getStatus().equals(1)){
            mimirEvent.setStatus(2);//事件结束
        }
        baseMapper.updateById(mimirEvent);
        return mimirEvent.getId();
    }

    /**
     * 获取事件列表(分页请传limit和page)
     * @param page        当前页码
     * @param limit       每页显示条数
     * @param cameraid    探头编号
     * @param sceneid     场景编号
     * @return
     */
    @Override
    public Page<Map<String, Object>> getAiEventList(Integer page, Integer limit, String cameraid, String sceneid) {
        Page<Map<String,Object>> resultPage = new Page<>();
        List<Map<String,Object>> resultList = new ArrayList<>();
        List<DbAiEvent> list = new ArrayList<>();
        //判断是否传了page和limit
        if (null != page && null != limit) {
            Page<DbAiEvent> iPage = new Page<>(page,limit);
            iPage = baseMapper.getAiEventList(iPage,cameraid,sceneid);
            list = iPage.getRecords();
            resultPage.setTotal(iPage.getTotal());
        } else {
            list = baseMapper.getAiEventList(cameraid,sceneid);
            resultPage.setTotal(list.size());
        }
        list.forEach(dbAiEvent -> {
            Map<String,Object> resultMap = formatAiEvent(dbAiEvent);
            resultList.add(resultMap);
        });
        resultPage.setRecords(resultList);
        return resultPage;
    }

    /**
     * 通过编号查询事件详情
     * @param eventid 事件编号
     * @return
     */
    @Override
    public DbAiEvent queryEventById(Long eventid){
        DbAiEvent aiEvent = baseMapper.selectById(eventid);
        return aiEvent;
    }

    /**
     * 查看事件详情
     * @param eventid  事件编号
     * @return
     */
    @Override
    public Map<String, Object> getEventInfo(Long eventid) {
        DbAiEvent aiEvent = queryEventById(eventid);
        if (null != aiEvent) {
            Map<String, Object> resultMap = formatAiEvent(aiEvent);
            //根据事件编号查看相关案卷图片详情
            List<EventImageVo> resultList = eventImageService.getFileInfo(eventid);
            if (null != resultList && resultList.size() > 0) {
                resultMap.put("eventImage",resultList);
            }
            return resultMap;
        }
        return null;
    }

    /**
     * 格式化事件信息
     * @param dbAiEvent
     * @return
     */
    private Map<String, Object> formatAiEvent(DbAiEvent dbAiEvent) {
        Map<String,Object> map = JSON.parseObject(JSON.toJSONString(dbAiEvent, SerializerFeature.WriteMapNullValue), Map.class);
        //事件状态
        if (null != dbAiEvent.getStatus()) {
            if (1 == dbAiEvent.getStatus()) {//事件持续中
                map.put("statusName","事件持续中");
            } else if (2 == dbAiEvent.getStatus()) {//事件结束
                map.put("statusName","事件结束");
            }
        }
        //创建时间
        if (null != dbAiEvent.getCreatedTime()) {
            String time = DateUtils.format(dbAiEvent.getCreatedTime(),DateUtils.DEFAULT_DATETIME_PATTERN);
            map.put("createdTimeStr",time);
        }
        //更新时间
        if (null != dbAiEvent.getUpdatedTime()) {
            String time = DateUtils.format(dbAiEvent.getUpdatedTime(),DateUtils.DEFAULT_DATETIME_PATTERN);
            map.put("updatedTimeStr",time);
        }
        //事件开始时间
        if (null != dbAiEvent.getStartTime()) {
            String time = DateUtils.format(dbAiEvent.getStartTime(),DateUtils.DEFAULT_DATETIME_PATTERN);
            map.put("startTimeStr",time);
        }
        //事件结束时间
        if (null != dbAiEvent.getEndTime()) {
            String time = DateUtils.format(dbAiEvent.getEndTime(),DateUtils.DEFAULT_DATETIME_PATTERN);
            map.put("endTimeStr",time);
        }
        return map;
    }

    /**
     *查询所有事件信息
     */
    @Override
    public List<DbAiEvent> queryEventList() {
        QueryWrapper<DbAiEvent> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        return baseMapper.selectList(wrapper);
    }

    /**
     * 根据场景编码查询事件集合
     * @param sceneCode  场景编码
     * @return
     */
    @Override
    public List<DbAiEvent> queryEventListBySceneCode(String sceneCode) {
        QueryWrapper<DbAiEvent> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("scene_id",sceneCode);
        return baseMapper.selectList(wrapper);
    }
}
